﻿using System;
using System.Collections.ObjectModel;
using System.Linq;

namespace OMIP.HMS.WPFBusiness
{
        /// <summary>
        ///         实现管理器的属性和方法
        /// </summary>
        public class EntityManager<E, M> : NotifyPropertyChangedObject where E : Entity<M> where M : class
        {
                public EntityManager()
                {
                        Entities = new ObservableCollection<E>();
                }

                #region 属性

                /// <summary>
                ///         获取用于绑定的实体集合
                /// </summary>
                /// <value>
                ///         用于绑定的实体集合
                /// </value>
                public ObservableCollection<E> Entities { get; private set; }

                private E _e;

                public E Entity
                {
                        get { return _e; }
                        set
                        {
                                _e = value;
                                this.NotifyPropertyChanged(i => i.Entity);
                                OnEntityChanged();
                        }
                }

                public M Model { get; set; }

                #endregion

                #region 事件

                public event EventHandler EntityChanged;

                #endregion

                #region 方法

                public void Insert(E e)
                {
                        if (Entities.Any(i => i.Id == e.Id))
                        {
                                return;
                        }
                        Entities.Add(e);
                }

                public void Insert()
                {
                        Insert(Entity);
                }

                public void Delete(E e)
                {
                        Entities.Remove(e);
                }

                public void Delete()
                {
                        Delete(Entity);
                }


                public void Clear()
                {
                        Entities.Clear();
                        Entity = null;
                }

                public void OnEntityChanged()
                {
                        if (EntityChanged != null)
                        {
                                EntityChanged(this, null);
                        }
                }

                #endregion
        }
}